package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.emoji.ParseEmojiMsgUtil;
import com.hemaapp.hm_FrameWork.emoji.SelectFaceHelper;
import com.hemaapp.hm_FrameWork.emoji.SelectFaceHelper.OnFaceOprateListener;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.YjnhImageWay;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.image.load.XtomImageTask;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 发布助农帖子、日志
 * 回复助农帖子、日志
 *
 * @author ZhangGuiyou
 *         Date: 2015-08-18 13:45
 */
public class ReleaseBlogActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_CAMERA = 0x01;
    private final static int REQUEST_ALBUM = 0x02;
    private final static int REQUEST_FLAG = 0x03;

    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.edt_title)
    EditText edtTitle;
    @Bind(R.id.tv_tag)
    TextView tvTag;
    @Bind(R.id.layout_header)
    LinearLayout layoutHeader;
    @Bind(R.id.edt_content)
    EditText edtContent;
    @Bind(R.id.image_grid)
    ImageGridView imageGrid;
    @Bind(R.id.tv_camera)
    TextView tvCamera;
    @Bind(R.id.tv_album)
    TextView tvAlbum;
    @Bind(R.id.tv_emoji)
    TextView tvEmoji;
    @Bind(R.id.face_viewpager)
    ViewPager faceViewpager;
    @Bind(R.id.msg_face_index_view)
    LinearLayout msgFaceIndexView;
    @Bind(R.id.layout_bottom)
    LinearLayout layoutBottom;
    @Bind(R.id.layout_emoji)
    View addFaceToolView;

    private int showType = 1;//显示类型：1发布帖子，2回复帖子, 3田家回复买家
    private String title = "";
    private String tag = "";
    private String content = "";
    private User user;
    private String blog_id;//帖子发布后的id
    private Reply reply;//用于跟楼回复时使用
    private String reply_id;//评论的id，用于上传评论图片
    //添加图片相关
//    private HemaImageWay imageWay;
    private YjnhImageWay imageWay;
    private Integer orderby = 0;//上传图片的排序
    //    private ArrayList<String> images = new ArrayList<>();//添加图片的地址
    private ArrayList<String> compressPaths;//压缩图片的路径，用于最后删除
    private ArrayList<ImgItemsBean> mImages = new ArrayList<>();//图片
    private AddImageAdapter mImgAdapter;
    // 表情相关
    private SelectFaceHelper mFaceHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_blog_release);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent it = new Intent(mContext, AlbumActivity.class);
                int size = mImages.size();
                it.putExtra("limitCount", 4 - size);// 图片选择张数限制
                it.putExtra("model", 1);// 图片是单选还是多选
                startActivityForResult(it, albumRequestCode);
            }
        };
    }

    @Override
    protected boolean onKeyBack() {
        if (addFaceToolView.getVisibility() == View.VISIBLE) {
            addFaceToolView.setVisibility(View.GONE);
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compressPaths != null)
            for (String path : compressPaths) {
                File file = new File(path);
                file.delete();
            }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        showType = mIntent.getIntExtra("type", 1);
        blog_id = mIntent.getStringExtra("blog_id");
        reply = (Reply) mIntent.getSerializableExtra("reply");
        if ((showType == 2 || showType == 3) && isNull(blog_id)) {
            XtomToastUtil.showShortToast(mContext, "获取信息失败");
            finish();
        }
    }

    @Override
    protected void setListener() {
        if (showType == 1) {
            titleText.setText("发布帖子");
            titleRightBtn.setText("发布");
            edtContent.setHint("请输入帖子内容");
        } else {
            titleText.setText("评论回复");
            titleRightBtn.setText("回复");
            edtContent.setHint("请输入回复内容");
            if (showType == 3) {
                layoutBottom.setVisibility(View.GONE);
            }
        }

        // 输入框点击监听
        edtContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                addFaceToolView.setVisibility(View.GONE);
            }
        });
        if (showType == 2 || showType == 3) {//回复帖子的时候隐藏头部分
            layoutHeader.setVisibility(View.GONE);
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
            case FILE_UPLOAD:
            case REPLY_ADD:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
            case FILE_UPLOAD:
            case REPLY_ADD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
                HemaArrayResult<String> sResult = (HemaArrayResult<String>) baseResult;
                blog_id = sResult.getObjects().get(0);
                if (mImages.size() > 0) {
                    orderby = 0;
                    fileUpload();
                } else {
                    XtomToastUtil.showShortToast(mContext, "发布成功！");
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_BLOG);
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1000);
                }
                break;
            case REPLY_ADD:
                HemaArrayResult<String> rResult = (HemaArrayResult<String>) baseResult;
                reply_id = rResult.getObjects().get(0);
                if (mImages.size() > 0) {
                    orderby = 0;
                    fileUpload();
                } else {
                    XtomToastUtil.showShortToast(mContext, "评论成功！");
                    //通知唠嗑列表刷新
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_REPLY_ADD);
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1000);
                }
                break;
            case FILE_UPLOAD:
                mImages.remove(0);
                if (mImages.size() > 0) {
                    fileUpload();
                } else {
                    EventBusMsg msg = new EventBusMsg();
                    if (showType == 1) {
                        XtomToastUtil.showShortToast(mContext, "发布成功！");
                        msg.setType(EventBusConfig.UPDATE_BLOG);
                    } else if (showType == 2 || showType == 3) {
                        XtomToastUtil.showShortToast(mContext, "评论成功！");
                        msg.setType(EventBusConfig.UPDATE_REPLY_ADD);
                    }
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1000);
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "发布失败," + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "发布失败，请稍后再试");
                break;
        }
    }

    /**
     * 上传多张照片
     */
    private void fileUpload() {
        String imagePath = mImages.get(0).getImgurl();
        if (showType == 1)
            getNetWorker().fileUpload(user.getToken(), "2", blog_id,
                    "0", orderby + "", "无", imagePath);
        else if (showType == 2 || showType == 3)
            getNetWorker().fileUpload(user.getToken(), "16", reply_id,
                    "0", orderby + "", "无", imagePath);
        orderby++;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                if (addFaceToolView.getVisibility() == View.VISIBLE)//如果有emoji显示，先隐藏
                    addFaceToolView.setVisibility(View.GONE);
                album(data);
                break;
            case REQUEST_CAMERA:// 拍照
                if (addFaceToolView.getVisibility() == View.VISIBLE)
                    addFaceToolView.setVisibility(View.GONE);
                camera();
                break;
            case REQUEST_FLAG:
                if (data != null) {
                    tag = data.getStringExtra("key");
                    if (!isNull(tag)) {
                        tvTag.setText(tag);
                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    OnFaceOprateListener mOnFaceOprateListener = new OnFaceOprateListener() {
        @Override
        public void onFaceSelected(SpannableString spanEmojiStr) {
            //当选择了一个emoji，将这个emoji添加到EditText
            if (null != spanEmojiStr) {
                edtContent.append(spanEmojiStr);
            }
        }

        @Override
        public void onFaceDeleted() {
            int selection = edtContent.getSelectionStart();
            String text = edtContent.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    edtContent.getText().delete(start, end);
                    return;
                }
                edtContent.getText().delete(selection - 1, selection);
            }
        }

    };

    private void camera() {
        String imagepath = imageWay.getCameraImage();
        new CompressPicTask().execute(imagepath);
    }

    private void album(Intent data) {
        if (data == null)
            return;
        ArrayList<String> imgList = data.getStringArrayListExtra("images");
        if (imgList == null)
            return;
        for (String img : imgList) {
            if (mImages.size() < 4) {
                new CompressPicTask().execute(img);
            }
        }
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn, R.id.ll_tag, R.id.tv_camera,
            R.id.tv_album, R.id.tv_emoji})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                title = edtTitle.getText().toString();
                //将输入内容中的emoji进行转换
                content = ParseEmojiMsgUtil.convertToMsg(edtContent.getText(), mContext).trim();
                if (content.length() == 0) {
                    XtomToastUtil.showShortToast(mContext, "内容不能为空");
                    break;
                }
                if (showType == 1) {//发布帖子，在当前页进行发布
                    if (title.length() == 0) {
                        XtomToastUtil.showShortToast(mContext, "标题不能为空!");
                    } else if (tag.length() == 0) {
                        XtomToastUtil.showShortToast(mContext, "标签不能为空!");
                    } else {
                        getNetWorker().blogAdd(user.getToken(),
                                "2", title, "无", "无", "无", "无", "无", "无", "无", tag, content, "无", "无", "无");
                    }
                } else if (showType == 2) {//回复
                    if (null == reply) {
                        getNetWorker().replyAdd(user.getToken(), "2", blog_id, content, "0");
                    } else {
                        content = "回复 " + reply.getNickname() + ":" + content;
                        getNetWorker().replyAdd(user.getToken(), "2", blog_id, content, reply.getId());
                    }
                } else if (showType == 3)
                    getNetWorker().replyAdd(user.getToken(), "2", blog_id, content, reply.getId());
                break;
            case R.id.ll_tag:
                Intent itTag = new Intent(mContext, BlogFlagActivity.class);
                startActivityForResult(itTag, REQUEST_FLAG);
                break;
            case R.id.tv_camera:
                if (mImages.size() < 4) {
                    imageWay.camera();
                }else
                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                break;
            case R.id.tv_album:
                if (mImages.size() < 4)
                    imageWay.album();
                else
                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                break;
            case R.id.tv_emoji:
                if (null == mFaceHelper) {
                    mFaceHelper = new SelectFaceHelper(ReleaseBlogActivity.this,
                            addFaceToolView);
                    mFaceHelper.setFaceOpreateListener(mOnFaceOprateListener);
                }

                if (addFaceToolView.getVisibility() == View.VISIBLE) {
                    addFaceToolView.setVisibility(View.GONE);
                    mInputMethodManager.showSoftInput(edtContent, 0);
                } else {
                    // 隐藏键盘
                    mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                            0);
                    addFaceToolView.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    if (compressPaths == null)
                        compressPaths = new ArrayList<>();
                    compressPaths.add(compressPath);

                    ImgItemsBean imageitem = new ImgItemsBean();
                    imageitem.setImgurl(compressPath);
                    imageitem.setImgurlbig(compressPath);
                    mImages.add(imageitem);
                    refreshImages();
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }

    /**
     * 刷新图片
     */
    private void refreshImages() {
        if (mImgAdapter == null) {
            mImgAdapter = new AddImageAdapter(mContext, mImages);
            mImgAdapter.setShowDelete(true);
            mImgAdapter.setShowAdd(false);
            imageGrid.setAdapter(mImgAdapter);
            mImgAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    mImages.remove(position);
                    mImgAdapter.notifyDataSetChanged();
                }
            });
        } else {
            mImgAdapter.notifyDataSetChanged();
        }
    }

}
